<template>
    <el-upload ref="upload" 
    :before-upload="beforeUploadVideo" 
    :on-success="handleVideoSuccess" 
    :on-progress="uploadVideoProcess"
    :limit="1" 
    :show-file-list="false"
    action="http://reg.vip.cpolar.cn/common/upload" accept=".pdf">
        <div v-if="pdfForm.pdf =='' && pdfFlag == false" >
            <span style="color: gray;">{{ props.text }}</span>
            <img src="../assets/img/矢量智能对象@2x(8).png" style="width: 1.2vw;height: 1.2vw;margin-left: 2vw;"/>
        </div>
        <div v-else-if="pdfForm.pdf !='' && pdfFlag == false" style="min-width: 3vw;" >{{ pdf.originalFilename}}<img src="../assets/img/矢量智能对象@2x(8).png" style="width: 1.2vw;height: 1.2vw;margin-left: 2vw;"/></div>
        <el-progress v-if="pdfFlag == true" :percentage="pdfUploadPercent"></el-progress>
    </el-upload>
</template>

<script setup lang="ts">
import {ref} from 'vue'
import {ElMessage } from 'element-plus';

const props = defineProps(['text','keyword']);

const pdfFlag = ref(false);
const pdf = ref({originalFilename:"",fileName:""})
const pdfForm = ref({
    pdf:"",
    pdfId:""
});
const pdfUploadPercent = ref(0);

const beforeUploadVideo = (file:any)=>{
    const isLt500M = file.size / 1024 / 1024  < 100;
    console.log(file.type)
    if (['application/pdf'].indexOf(file.type) == -1) {
        ElMessage.error('请上传正确的文件格式');
        return false;
    }
    if (!isLt500M) {
        ElMessage.error('上传pdf大小不能超过100MB哦!');
        return false;
    }
}

const handleVideoSuccess = (res:any, file:any)=>{    
    pdfFlag.value = false;
    pdfUploadPercent.value = 0;                           //获取上传图片地址
    console.log(res);
    if(res.code == 200){
        pdfForm.value.pdfId = res.newFileName;
        pdfForm.value.pdf = res.url;
        pdf.value = res;
    }else{
        ElMessage.error('pdf上传失败，请重新上传！');
    }
}
const uploadVideoProcess = (event:any, file:any, fileList:any)=>{
    pdfFlag.value = true;
    pdfUploadPercent.value = file.percentage.toFixed(0);
}

const getPdfData = ()=>{
    if(pdf.value.fileName=="" || pdf.value.fileName==undefined)
    {
        ElMessage({showClose: true,message: '还有未上传的pdf文件，请检查',type: 'error'});
        throw new Error("还有未上传的pdf文件，请检查");
    }
    let data = {keyWord: props.keyword, url: pdf.value.fileName, fileType: 2, subTitle: pdf.value.originalFilename}
    return data;
}

defineExpose({getPdfData})
</script>